define([ './module' ], function(sysrolemodule) {
	'use strict';





	//系统角色权限功能查询出所有的权限
	sysrolemodule.controller('sysroleaction',serverSysModuleActionCtrl);
	function serverSysModuleActionCtrl($state,$scope,$http,$location) {
		$scope.gtparams = [];
		var operate = $location.search().operate;
		if (operate != undefined && operate == "edit") {
			//控制保存按钮显示
			$scope.updatebtn = {show: true};
			$scope.sysrolename=$location.search().sysrolename;
			$scope.title = '正在对角色--' + $scope.sysrolename+ '--权限进行编辑';
			var sysroleid = $location.search().sysroleid;
			if (sysroleid != undefined && sysroleid != "") {
				$http({
					method: 'POST',
					url: '../mall/sysroleaction/findAll'
				}).success(function (data, status, headers, config) {
					if (data.sucflag) {
						$scope.gtparams = data.beanlist;
						$scope.findSysRoleAction();
						$scope.updatebtn = {show: true};

					}
				}).error(function (data, status, headers, config) {
					$scope.errors = {
						show: true,
						msg: '系统异常'
					}
				});

				//获取角色已有的权限信息
				$scope.findSysRoleAction=function(){
					$http({
						method: 'POST',
						url: '../mall/sysroleaction/find',
						data:{
							'sysroleid':sysroleid
						}
					}).success(function (data, status, headers, config) {
						if (data.sucflag) {
							angular.forEach(data.beanlist,function(d,i,a){
								$scope.selected.push(d.sysmoduleactionid);
							});
						}
					}).error(function (data, status, headers, config) {
						$scope.errors = {
							show: true,
							msg: '系统异常'
						}
					});
				}



				//更新角色的权限关系
				$scope.update = function () {
					var sysmoduleactionid = $scope.selected.join(",");
					$http({
						method: 'POST',
						url: '../mall/sysroleaction/updateMulitRoleModuleAction',
						data: {
							'sysmoduleactionid': sysmoduleactionid,
							'sysrolename': $scope.sysrolename,
							'sysroleid': sysroleid
						}
					}).success(function (data, status, headers, config) {
						if (data.sucflag) {
							$scope.info = {
								show: true,
								msg: '角色权限更新成功'
							}
							$location.path('/sysrolement');
						}else{
							$scope.errors = {
								show: true,
								msg: data.msg
							}
						}
					}).error(function (data, status, headers, config) {
						$scope.errors = {
							show: true,
							msg: '系统异常'
						}
					});

				}


				$scope.selected=[];

				var updateSelected=function(action,id){
					if(action=='add'&&$scope.selected.indexOf(id)==-1){
						$scope.selected.push(id);
					}
					if(action=='remove'&&$scope.selected.indexOf(id)!=-1){
						var idx=$scope.selected.indexOf(id);
						$scope.selected.splice(idx,1);
					}
				}

				$scope.updateSelection=function($event,id){
					var checkbox=$event.target;
					var action=(checkbox.checked?'add':'remove');
					updateSelected(action,id);
				}
				$scope.isSelected=function(id){
					return $scope.selected.indexOf(id)>=0;
				}


			}
		}
	}




	//系统角色控制器
	sysrolemodule.controller('sysrole',serverSysModuleCtrl);
	function serverSysModuleCtrl($state,$scope,$http,$location){
		//通过location中的operate参数区分操作行为
		var operate=$location.search().operate;
		if(operate!=undefined&&operate=="save"){
			//控制保存按钮显示
			$scope.savebtn={show:true};
			$scope.title='添加系统角色';
			$scope.status="1";

			//保存数据方法
			$scope.save=function(){
				var sysrolename=$scope.sysrolename;
				if(sysrolename==undefined){
					$scope.errors={
						show:true,
						msg:'请输入角色名称'
					}
					return false;
				}
				var note=$scope.note;
				if(note==undefined){
					$scope.errors={
						show:true,
						msg:'请输入角色说明'
					}
					return false;
				}
				$http({
					method:'POST',
					url:'../mall/sysrole/save',
					data:{
						'sysrolename':sysrolename,
						'status':$scope.status,
						'note':note
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.info={
								show:true,
								msg:'角色添加成功'
						}
						$location.path('/sysrolement');
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});

			}

		}
		//如果operate是edit则执行保存行为
		if(operate=='edit'){
			var id=$location.search().id;
			if(id!=undefined&&id!=""){
				$http({
					method:'POST',
					url:'../mall/sysrole/find',
					data:{
						'id':id
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.title='正在对--'+data.bean.sysrolename+'--进行编辑';
						$scope.sysrolename=data.bean.sysrolename;
						$scope.status=data.bean.status;
						$scope.note=data.bean.note;
						$scope.updatebtn={show:true};
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
				//更新数据方法
				$scope.update=function(){
					var sysrolename=$scope.sysrolename;
					if(sysrolename==undefined){
						$scope.errors={
							show:true,
							msg:'请输入角色名称'
						}
						return false;
					}
					var note=$scope.note;
					if(note==undefined){
						$scope.errors={
							show:true,
							msg:'请输入角色说明'
						}
						return false;
					}
					$http({
						method:'POST',
						url:'../mall/sysrole/update',
						data:{
							'sysrolename':sysrolename,
							'status':$scope.status,
							'note':note,
							'id':id
						}
					}).
					success(function(data,status,headers,config){
						if(data.sucflag){
							$scope.info={
								show:true,
								msg:'角色更新成功'
							}
							$location.path('/sysrolement');
						}
					}).
					error(function(data,status,headers,config){
						$scope.errors={
							show:true,
							msg:'系统异常'
						}
					});
				}

			}


		}
		$scope.remove=function(index){
			$scope.gtparams.splice(index,1);
		}

	}

	//系统角色查询
	sysrolemodule.controller('sysrolement',serverSysModuleMentCtrl);
	//查询列表数据
	function serverSysModuleMentCtrl($state,$http,$location,$compile,$scope,$rootScope,$resource,DTOptionsBuilder,DTColumnBuilder,DTAjaxRenderer){
		$scope.title="系统角色列表";
		var vm=this;
		vm.message='';
		vm.someClickHandler = someClickHandler;
		vm.selected={};
		vm.selectAll=false;
		vm.toggleAll=toggleAll;
		vm.toggleOne=toggleOne;
		vm.dtInstance={};
		var titleHtml='<input type="checkbox" ng-model="showCase.selectAll" ng-click="showCase.toggleAll(showCase.selectAll,showCase.selected)">';
		vm.dtOptions=DTOptionsBuilder.newOptions().withOption('ajax',{
			type:'POST',
			url:'../mall/sysrole/findByPage',
			dataSrc:'data'
		})
		.withOption('processing',false)
		.withOption('paging',true)
		.withOption('serverSide',true)
		.withOption('createdRow',function(row,data,dataIndex){
			$compile(angular.element(row).contents())($scope);
		})
		.withOption('headerCallback', function(header) {
      if (!$scope.headerCompiled) {
          $scope.headerCompiled = true;
          $compile(angular.element(header).contents())($scope);
      }
    })
    .withOption('stateSave', true)
    .withOption('rowCallback',rowCallback)
		.withPaginationType('full_numbers')
		.withLanguageSource('./app/language/chinese.json');
		$scope.$on('handleRequest',function(){
		});
		vm.dtColumns=[
				  DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function(data,type,full,meta){
					  vm.selected[full.id]=false;
					  return '<input type="checkbox" ng-model="showCase.selected['+data.id+']" ng-click="showCase.toggleOne(showCase.selected)">';
				  }),
				  DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
				  DTColumnBuilder.newColumn('sysrolename').withTitle('角色名称').notSortable(),
			      DTColumnBuilder.newColumn('note').withTitle('说明').notSortable(),
				  DTColumnBuilder.newColumn('status').withTitle('状态').notSortable(),
				  DTColumnBuilder.newColumn('updatetime').withTitle('更新时间').notSortable(),
				  DTColumnBuilder.newColumn('version').withTitle('版本号').notSortable(),
				  DTColumnBuilder.newColumn(null).withTitle('操作').notSortable().renderWith(actionHtml)
		];

		function actionHtml(data,type,full,meta){
			return "<button class='btn btn-warning' ng-click=\"edit('"+data.id+"')\"><i class='fa fa-edit'></i></button>"+
				"<button sytle='margin-left:10px' class='btn btn-success' ng-click=\"sysroleaction('"+data.id+"','"+data.sysrolename+"')\">角色权限</button>";
		}
		function reloadData(){
			var resetPaging = false;
	        vm.dtInstance.reloadData(callback, resetPaging);
		}
		function callback(data){
		}

		/**
		 * 复杂搜索刷新数据
		 */
		function searchReloadData(){
			var resetPaging=false;
			var searchParams={
				isCustomSearch:1,
				name:''
			};
			if($scope.name!=undefined){
				searchParams.name=$scope.name;
				vm.dtOptions['ajax'].data=searchParams;
				vm.dtInstance.reloadData(callback, resetPaging);
			}
		}

		/**
		 * 表格
		 */
		$scope.searchdataTableCustom=function(){
			searchReloadData();
		}

		/**
		 * 系统角色权限
		 */
		$scope.sysroleaction=function(id,name){
			$location.path('/sysroleaction').search({'operate':'edit','sysroleid':id,'sysrolename':name});
		}

		//表格中编辑按钮
		$scope.edit=function(id){
			$location.path('/sysrole').search({'operate':'edit','id':id});
		}


		$scope.save=function(){

			$location.path('/sysrole').search({'operate':'save'});
		}

		/**
		 * 删除记录
		 */
		$scope.del=function(){
			var i=0;
			var ids=[];
			angular.forEach(vm.selected, function(data,index,array){
				if(data){
					i++;
					ids.push(index);
				}
			});
			if(i==0){
				$scope.errors={
						show:true,
						msg:'请选择一条记录'
				}
			}else{
				$scope.errors={
						show:false
				}
				//批量删除数据
				var idstrs=ids.join(",");
				$http({
					method:'POST',
					url:'../mall/sysrole/del',
					data:{
						'id':idstrs
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.info={
								show:true,
								msg:'删除成功'
						}
						reloadData();
					}

				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}
		}

		/**
		 * 列表全选
		 */
		function toggleAll(selectAll,selectedItems){
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					selectedItems[id]=selectAll;
				}
			}
		}
		/**
		 * 列表单选
		 */
		function toggleOne(selectedItems){
			var me=this;
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					if(!selectedItems[id]){
						me.selectAll=false;
					}
				}
			}
			me.selectAll=true;
		}

		function someClickHandler(info) {
	        vm.message = info.id + ' - ' + info.name;
	    }
		/**
		 * 单击列表某行回调
		 */
		function rowCallback(nRow,aData,iDisplayIndex,iDisplayIndexFull){
			$('td', nRow).unbind('click');
	        $('td', nRow).bind('click', function() {
	            $scope.$apply(function() {
	                vm.someClickHandler(aData);
	            });
	        });
	        return nRow;
		}

	}
});
